from fastapi import APIRouter
from src.utils.common_response import APIResponse
from ..models import UserInfo, Menu
from fastapi import Depends
from ..core import get_current_user
from ..schemas import MenuPermissionSchema

router = APIRouter()


@router.get("/auth", description="获取菜单，按钮权限")
async def get_menu(user: UserInfo = Depends(get_current_user)):
    if user.is_superuser:
        menus = await Menu.filter(is_delete=False).all().prefetch_related('children').order_by('menu_sort')
        nav = [await MenuPermissionSchema.from_orm_recursive(menu) for menu in menus]
        buttons = await Menu.filter(type=2)
        authoritys = [item.permission for item in buttons]

    else:
        roles = await user.roles.all()
        catalog_ids = []
        menus_ids = []
        buttons = []

        for role in roles:
            catalog_ids += await role.menus.filter(type=0).values_list('id', flat=True)
            menus_ids += await role.menus.filter(type=1).values_list('id', flat=True)
            buttons += await role.menus.filter(type=2)
        print("catalog_ids:::",catalog_ids)
        menus_qs = await Menu.filter(id__in=list(set(catalog_ids)))
        print("menus_qs:::",menus_qs)
        nav = [await MenuPermissionSchema.from_orm_recursive(menu, menus_ids) for menu in menus_qs]
        authoritys = [item.permission for item in buttons]
        authoritys = list(set(authoritys))

    return APIResponse(nav=nav, authoritys=authoritys)
